import { getInfo,getUserByIdDetail } from "@/api/user"
import { getToken, removeToken, setToken } from "@/utils/auth"
import { Message } from "element-ui"
import { login } from '@/api/user'
import { resetRouter } from "@/router"

export default {
  namespaced:true,//开启命名空间
  state:{
    token:getToken()||'',
    userinfo:{}
  },
  mutations:{
    updateToken(state,token){
      state.token=token
      setToken(token)
    },
    delToken(state){
      state.token=''
      removeToken()
    },
    updateUserInfo(state,info){
      state.userinfo=info
    },
    delUserInfo(state){
      state.userinfo={}
    },
  },
  actions:{
    async  initToken(context,formData){
      const res= await login(formData)
      if(res.code!==10000) return Message.error(res.message)
      // console.log(res);
      Message.success(res.message)
      context.commit('updateToken',res.data)
    },
    async getUserInfo(context){
      try {
        const res =await getInfo()
        const info =await getUserByIdDetail(res.data.userId)
        context.commit('updateUserInfo',{...res.data,...info.data})
        return res.data.roles.menus
      } catch (error) {
        console.log(error);
      }
    },
    //退出登录，清空token用户信息
    logout(context){
      context.commit('delToken')
      context.commit('delUserInfo')
      //路由重置
      resetRouter()
    }
  }
}